import router from '@/router'
import Axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { getToken, removeToken } from './auth'
import chalk from 'chalk'

export const http = Axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 300000
})
export type Pagination<T = any> = {
  list: T[]
  totalCount: number
}

export type HttpResponse<T = any> = {
  code: number
  data: T
  msg: string
}

export type JsonHttpResponse<T = any> = {
  code: number
  data: T
  message: string
}

export type HttpResponsePagination<T = any> = {
  code: number
  data: Pagination<T>
  msg: string
}

http.interceptors.request.use(requestInterceptor)
http.interceptors.response.use(responseInterceptors)

function requestInterceptor(config: InternalAxiosRequestConfig) {
  config.headers['token'] = getToken()

  // 像[]这种参数，浏览器会有特殊解析，所以需要编码
  if (config.method?.toLocaleLowerCase() === 'get') {
    let url = config.url + '?'
    for (const key in config.params) {
      const val = config.params[key]
      if (val === '' || val === undefined || val === null) continue
      url += `${key}=${encodeURIComponent(val)}&`
    }
    config.params = {}
    config.url = url.slice(0, -1)
  }

  return config
}

function responseInterceptors(res: AxiosResponse) {
  if (__DEV__) {
    console.log(
      `${chalk.hex(res.status === 200 ? '#10ac84' : '#ee5253').bold('%d')} ${chalk
        .hex('#341f97')
        .bold.underline('%s')}`,
      res.status,
      res.config.url,
      res.data
    )
  }

  // handle status
  switch (res.status) {
    case 401:
      removeToken()
      router.push({ name: 'login' })
      return res
  }

  // handle code
  if (!res.headers['content-type'] || res.headers['content-type'].includes('application/json')) {
    switch (res.data.code) {
      case 401:
        removeToken()
        router.push({ name: 'login' })
        return res
    }
  }

  return res
}
